<template>
  <div>
    <!-- 搜索 -->
    <!-- 旧件出库-- 车厂-->
    <TopFilter ref="TopFilterss" :list="topFilterInit" :cols="3" :collapse="collapse" labelWidth="120"
      @filterChange="changeHandle" @resetChange="resetHandle"></TopFilter>
    <!-- table -->
    <FilterTable ref="table" :columns="columns" :params="fetchParams" :dataSource="dataList" :datakey="'records'"
      :fetchapi="fetchApi" :onColumnsChange="columns => (this.columns = columns)" :onRowSelectChange="selectChange"
      :is-select-column="false">
      <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="add">新增</multiuse-button>
       <!--  <multiuse-button size="small" type="primary" :click="exportFileBtn.bind()">导出</multiuse-button> -->
      </template>
    </FilterTable>

    <!-- 服务中心选择 -->
    <BaseDialog :visible.sync="selectDelearFlag" :title="'服务中心选择'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <DealerList @close="Delearclose" @save="Delearsave"></DealerList>
    </BaseDialog>
    <!-- 供应商选择 -->
    <BaseDialog :visible.sync="suppliers" :title="'供应商选择'" width="850px" destroyOnClose :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
        <SupplierList @close="suppliersClose" @save="suppliersSave" ></SupplierList>
      </BaseDialog>
    <Drawer :visible.sync="visibleAdd" :title="'旧件出库'" destroyOnClose width="60%"
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <AddForm @close="closeAdd" @save="saveAdd"></AddForm>
    </Drawer>
    <Drawer :visible.sync="visibleEdit" :title="'编辑'" destroyOnClose width="60%"
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <editForm @close="close" @save="save" :rowData="outId" ></editForm>
    </Drawer>
    <Drawer :visible.sync="visibleDetail" :title="'明细'" destroyOnClose width="60%"
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <DetailFrom @close="close2" :rowData="outId"></DetailFrom>
    </Drawer>
    <!-- 打印出库单 -->
    <BasePrint ref="templateEncasement" :data="waitEncasementList" template="waitReturnLabel/printOutPackage" />
  </div>
</template>
<script>

import moment from "moment";
import { getUserInfo} from '@/api/login/index';
import AddForm from './AddForm.vue';
import editForm from './editForm.vue';
import SupplierList from '@/pages/claimDemage/tools/SuppliersList.vue';
import DealerList from '@/pages/claimDemage/tools/DealerList.vue';
import DetailFrom from './DetailFrom.vue';
import { getListByPage, getListForExport, generateReturnBoxList,} from '@/api/usedPartsReturnManage/usedPartsReturn_OEM/usedPartsOutOfStock';
import { exportExcelFile } from '@/utils/index';
import { getPartType, getListByExample } from '@/api/dictionary/index.js';
import { getAppId } from '@/assets/js/auth';
import { dictionary } from '@/utils/dictMixin';
export default {
  mixins: [dictionary],
  components: {
    AddForm,
    editForm,
    DetailFrom,
    DealerList,
    SupplierList,
  },
  data() {
    return {
      waitEncasementList:{
        rows:[{

        }],
        createdByName: null
      },
      userName:null,
      outId: null,
      //dataType:{},
      dataList: [],
      visible: false,
      selectDealerData: [],
      suppliers: false,
      dealerData: [],
      selectDelearFlag: false,
      visibleDetail: false,
      visibleEdit: false,
      collapse: true,
      topFilterInit: this.topFilterInitFun(),
      fetchApi: getListByPage,
      columns: this.creatHeader(),
      fetchParams: {
        xhrAbort: true,
        dealerName:null
      }, //ipa 接口
      selectedRows: [], //选中服务站
      visibleAdd: false
    };
  },
  /* created() {
    this.chuqi();
    this.fetchParams.beginDlDate = moment().startOf('week').format('YYYY-MM-DD HH:mm:ss');
    this.fetchParams.endDlDate = moment().endOf('week').format('YYYY-MM-DD HH:mm:ss');
  }, */
  async created() {
    await this.chuqi2();
    this.init();
  },
  methods: {
    init() {
      //用户信息
      getUserInfo().then(res=>{
        if (res.resultCode === 200) {
        this.userInfo = res.data.userInfo;
      } else {
        this.$notify.error({ title: '提示信息', message: '获取制单人信息失败!' });
      }
    //  console.log('this.userInfo',this.userInfo)
     // console.log('this.userInfo',this.userInfo.userName)
      this.userName =this.userInfo.userName;
     // console.log('this.userInfo',this.userName)
      })


    },
     //出库类型下拉框
     async chuqi2() {
      console.log("===== 获取下拉框数据 ====== ")
      const res = await getPartType({ type: 5523 });
      console.log("==========",res)
      if (res.resultCode == 200) {
        this.topFilterInit.find(x => x.fieldName == 'outType').itemList = res.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
      }
    },
    // 导出
   /*  async exportFileBtn() {
      let json = Object.assign({}, { CODE: 'CODE_00000176' }, this.fetchParams);
      let res = await exporturl(json);
      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }
    }, */
    SelectDelear() {
      this.selectDelearFlag = true;
    },
    //关闭
    Delearclose() {
      this.selectDelearFlag = false;
    },
    resetHandle(val) {
      this.dealerData = [];
      this.selectDealerData = [];
      this.fetchParams.dealerName = null;
      this.fetchParams = Object.assign({}, this.fetchParams, val, { xhrAbort: false });
    },
    //保存
    Delearsave(obj) {
      console.log('选择数据传递', obj);
      this.dealerData = obj;
      this.selectDealerData = [];
      obj.forEach(item => {
       // console.log("dealerShortname"+item.dealerShortname)
        this.selectDealerData.push(item.dealerCompanyCode);
        this.fetchParams.dealerName = item.dealerName
;
      });


        console.log("dealerName", this.fetchParams.dealerName)

      this.selectDelearFlag = false;
    },
    //旧件仓库下拉框
    /*  async chuqi() {
       console.log("===== 获取下拉框数据 ====== ")
       const res = await getPartType({ type: 5523 });
       console.log("==========",res.data);
       if (res.resultCode == 200) {
         this.topFilterInit.find(x => x.fieldName == 'outType').itemList = res.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
       }
       // const res1 = await getListByExample();
       // console.log("==========",res)
       // if (res1.resultCode == 200) {
       //   this.topFilterInit.find(x => x.fieldName == 'whCode').itemList = res1.data.map(y => ({ text: y.whName, value: y.whCode }));
       // }

     }, */
     //供应商选择
     selectSuppliersCode() {
      this.suppliers = true;
    },
    suppliersClose(){
      this.suppliers = false;
    },
    suppliersSave(obj) {
      //console.log(obj[0].bjgybm)
      //this.topFilterInit.find(x => x.fieldName == 'supCode').initialValue = obj[0].bjgybm;
      this.topFilterInit.find(x => x.fieldName == 'supName').initialValue = obj[0].bjgyjc;
      this.suppliers = false;
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      console.log(this.selectedRows);
    },
    close() {
      this.visibleEdit = false;
    },
    close2() {
      this.visibleDetail = false;
    },
    chooseOrderNo(val) {
      this.outId = val;
      console.log("编辑ID", val)
     // this.dataType = val.partStatus;
      this.visibleEdit = true;

    },
    chooseOrderNo2(val) {
      this.outId = val;
      console.log("明细ID", val)
      this.visibleDetail = true;
    },
   /*  async examineInList(val) {
      console.log('@@@@@',val)
      var res = await generateReturnBoxList({outId: val})
      if (res.resultCode === 200) {
        this.waitEncasementList.rows = res.data.dtlList;
        this.$nextTick(() => {
          this.$refs.templateEncasement.EXCUTE_PRINT();
        });
      }
    }, */
    async examineInList(val) {
      console.log('@@@@@',val.outId)
      var res = await  generateReturnBoxList({id: val.outId})
      if (res.resultCode === 200) {
        //console.log('@@@@@11',res.data)
        //console.log('@@@@@22',res.data.dtlList)
        this.waitEncasementList.rows = res.data;
        this.waitEncasementList.createdByName = this.userName;
        this.$nextTick(() => {
          this.$refs.templateEncasement.EXCUTE_PRINT();
        });
      }
    },
    save() {
      this.visibleEdit = false;
      this.fetchParams = { ...this.fetchParams };
    },
    add() {
      this.visibleAdd = true;
    },
    closeAdd() {
      this.visibleAdd = false;
      this.fetchParams = { ...this.fetchParams };
    },
    saveAdd() {
      this.visibleAdd = false;
      this.fetchParams = { ...this.fetchParams };
    },
    //搜索数据
    topFilterInitFun() {
      return [
        { type: 'INPUT', label: '出库单号', fieldName: 'outNo', placeholder: '请输入出库单号...', initialValue: '' },
        {
          type: 'SELECT',
          label: '出库类型',
          fieldName: 'outType',
          placeholder: '请选择出库类型...',
          initialValue: '',
          itemList:[],
          //rules: [{message: '请选择出库类型...', trigger: 'change' }],
        },
        {
          type: 'RANGE_DATE',
          label: '出库日期',
          fieldName: 'beginOutDate|endOutDate',
          placeholder: '请输入',
          initialValue: [],
          rules: [{ required: false, message: '请选择日期', trigger: 'change' }]
        },
      /*   {
          type: 'RANGE_DATE',
          label: '保存时间',
          fieldName: 'beginSaveDate|endSaveDate',
          placeholder: '请输入',
          initialValue: [
            moment()
              .startOf('week')
              .format('YYYY-MM-DD HH:mm:ss'),
            moment()
              .endOf('week')
              .format('YYYY-MM-DD HH:mm:ss')
          ],
          rules: [{ required: true, message: '请选择日期', trigger: 'change' }]
        }, */
        { type: 'SELECT', label: '状态', fieldName: 'isOutPart', placeholder: '请选择', itemList: [{ text: '未出库', value: '30151001' }, { text: '已出库', value: '30151003' }],initialValue: '' },
        {
          type: 'INPUT',
          label: '服务中心',
          //fieldName: 'dealerName',
          render: (p) => {
            return (
              <div>
                <el-select v-model={this.selectDealerData} disabled={true} multiple placeholder="请选择">
                  {this.dealerData.map((item) => (
                    <el-option key={item.dealerCode} label={item.dealerShortname} value={item.dealerCompanyCode} />
                  ))}
                </el-select>
                <multiuse-button style="position: absolute;right: 0;height:100%" icon="el-icon-search" onClick={() => this.selectDelearFlag = true} />
              </div>
            );
          },
        },
        { type: 'INPUT',
          label: '供应商',
          fieldName: 'supName',
          placeholder: '请选择供应商...',
          readonly: true,
          initialValue:'',
          unitRender: p => {
            return (
              <div>
                <multiuse-button icon="el-icon-search" onClick={() => this.selectSuppliersCode()} />
              </div>
            );
          }
        },
       /*  { type: 'INPUT',
          label: '供应商',
          fieldName: 'supCode',
          placeholder: '请选择供应商...',
          readonly: true,
          initialValue:'',
          hidden:true,
      } */

      ];
    },
    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = Object.assign({dealerName: this.odealerName}, this.fetchParams,  val, { xhrAbort: false });
      console.log(val);
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          width: 150,
          dataIndex: 'column-action',
          render: (props, h) => {
            return (
              <div style="text-align:center">
                <multiuse-button size="mini" type="text" onClick={() => this.chooseOrderNo(props.row)} disabled={props.row.isOutPart === 30151003}>
                  编辑
                </multiuse-button>
                <el-divider direction="vertical" />
                <multiuse-button size="mini" type="text" onClick={() => this.chooseOrderNo2(props.row)}>
                  明细
                </multiuse-button>
                <el-divider direction="vertical" />
                <multiuse-button size="mini" type="text" onClick={() => this.examineInList(props.row)}>
                    打印
                  </multiuse-button>
              </div>
            );
          }
        },

        { title: '出库单号', dataIndex: 'outNo', sorter: true },
        { title: '出库类型', dataIndex: 'outType', sorter: true,dictItems: this.createDictList('5523')
        /* showOverflowTooltip: true,
         dictItems: this.createDictList('5523'),
          render: props => {
            return <span>{this.createDictText(props.row.outType, '5523')}</span>;} */
        },
        { title: '状态', dataIndex: 'isOutPart', sorter: true ,dictItems: this.createDictList('3015')},
        { title: '供应商代码', dataIndex: 'supCode', sorter: true },
        { title: '供应商名称', dataIndex: 'supName', sorter: true ,width:200},
        { title: '出库数量', dataIndex: 'outPartCount', sorter: true, width:80},
        { title: '出库人', dataIndex: 'createdBy', sorter: true },
        { title: '出库日期', dataIndex: 'outDate', sorter: true ,width:200},
        { title: '备注', dataIndex: 'outRemarks', sorter: true }
      ];
    }
  }
};
</script>

<style lang="less" scoped>

</style>
